package com.android.cattlefarm;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.cattlefarm.db.AddDB;
import com.android.cattlefarm.util.Constants;
import com.android.cattlefarm.util.ExportEntity;
import com.android.cattlefarm.util.FileEntity;
import com.android.cattlefarm.util.FileUtil;
import com.android.cattlefarm.util.ImportEntity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class MergeActivity extends BaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private ListView mListView;
    private List<FileEntity> filesList = new ArrayList<>();
    private List<FileEntity> selectedList = new ArrayList<>();
    private FileAdapter fileAdapter;
    private String fileParentPath;
    private String currentPath;
    private Button saveBtn, createBtn;
    private String selectFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import);
        mListView = (ListView) findViewById(R.id.import_list);
        saveBtn = (Button) findViewById(R.id.title_right);
        createBtn = (Button) findViewById(R.id.title_create);
        mListView.setOnItemClickListener(this);
        saveBtn.setOnClickListener(this);
        createBtn.setOnClickListener(this);
        createBtn.setVisibility(View.VISIBLE);
        saveBtn.setVisibility(View.VISIBLE);
        saveBtn.setText("合并");
        setCurrentFile(ImportActivity.ROOT_FILE_PATH);
    }

    private void setCurrentFile(String path) {
        if (path == null || path.equals("")) return;
        filesList.clear();
        selectedList.clear();
        File file = new File(path);
        currentPath = path;
        fileParentPath = file.getParentFile().getAbsolutePath();
        if (file.isDirectory()) {
            File flist[] = file.listFiles();
            for (int i = 0; i < flist.length; i++) {
                File currentFile = flist[i];
                FileEntity fileEntity = new FileEntity();
                fileEntity.setPath(currentFile.getAbsolutePath());
                fileEntity.setName(currentFile.getName());
                fileEntity.setModifyTime(currentFile.lastModified());
                if (currentFile.isDirectory()) {
                    fileEntity.setIsDirectory(true);
                    try {
                        fileEntity.setFileCount(currentFile.listFiles().length);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                filesList.add(fileEntity);
            }
        }
        fileAdapter = new FileAdapter(this, filesList);
        fileAdapter.setSelected(true);
        mListView.setAdapter(fileAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v == createBtn) {
            final EditText inputServer = new EditText(this);
            inputServer.setMaxHeight(120);
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
            builder.setTitle("输入文件名称").setView(inputServer)
                    .setNegativeButton("取消", null);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    if (inputServer.getText().toString().trim().equals("")) return;
                    File file = new File(currentPath + File.separator + inputServer.getText().toString());
                    if (!file.exists()) {
                        boolean create = file.mkdirs();
                        if (create) {
                            inputServer.setText("");
                            showMessage("文件夹创建成功");
                            setCurrentFile(currentPath);
                        }
                    }
                }
            });
            builder.show();
        } else {
            if (currentPath != null) {

                if (selectedList == null || selectedList.size() < 2) {
                    showMessage("至少选择两个文件");
                    return;
                }
                final EditText inputServer = new EditText(this);
                inputServer.setMaxHeight(120);
                inputServer.setText(getFileName());
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
                builder.setTitle("输入文件名称").setView(inputServer)
                        .setNegativeButton("取消", null);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        if (inputServer.getText().toString().trim().equals("")) {
                            showMessage("请输入文件名称");
                            return;
                        }
                        selectFilePath = inputServer.getText().toString();
                        showLoading();
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                getAllData();
                            }
                        });
                    }
                });
                builder.show();
            }
        }
    }

    private void getAllData() {
        List<ExportEntity> allData = new ArrayList<>();
        for (FileEntity fileEntity : selectedList) {
            if (fileEntity.isSelected()) {

                try {
                    List<ExportEntity> tempData = getValueList(fileEntity.getPath());
                    if (tempData != null) {
                        if (allData.size() == 0) allData.addAll(tempData);
                        else if (allData.size() >= tempData.size())
                            for (int i = 0; i < tempData.size(); i++) {
                                allData.get(i).update(tempData.get(i));
                            }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (allData.size() == 0) {
            showMessage("文件中无数据");
        } else {
            saveFile(selectFilePath, allData);
        }
        hideLoading();
    }

    private String getFileName() {
        AddDB importDB = new AddDB(this);

        List<ExportEntity> dataList = importDB.queryExportList();
        importDB.closeDataBase();
        if (dataList == null || dataList.size() == 0) return "";
        ExportEntity entity = dataList.get(0);
        StringBuffer sb = new StringBuffer();
        sb.append(entity.getCowfarmName());
        sb.append("_");
        sb.append(entity.getCowfarmNum());
        return sb.toString();
    }

    private void saveFile(String fileName, List<ExportEntity> allData) {
        if (createTempXls(currentPath + File.separator + fileName + ".xls", allData)) {
            showMessage("保存成功");
            setCurrentFile(currentPath);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileEntity fileEntity = (FileEntity) mListView.getAdapter().getItem(position);
        if (fileEntity == null) return;

        if (fileEntity.isDirectory())
            setCurrentFile(fileEntity.getPath());
        else {
            if (fileEntity.getName().endsWith("xls")) {
                filesList.get(position).setIsSelected(!filesList.get(position).isSelected());
                if (filesList.get(position).isSelected()) {
                    if (selectedList.size() >= 10) {
                        showMessage("最多选择十个文件");
                        return;
                    }
                    selectedList.add(filesList.get(position));
                } else {
                    try {
                        selectedList.remove(filesList.get(position));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                fileAdapter.notifyDataSetChanged();
            }
        }
    }

    public void backClick(View v) {
        if (fileParentPath != null && !fileParentPath.equals(ImportActivity.ROOT_FILE_PARENT_PATH)) {
            setCurrentFile(fileParentPath);
        } else {
            finish();
        }
    }

    private List<ExportEntity> getValueList(String filePath) {
        List<ExportEntity> info = new ArrayList<>();
        try {
            Workbook book = Workbook.getWorkbook(new File(filePath));
            Sheet sheet = book.getSheet(0);
            int row = sheet.getRows();
            int columns = sheet.getColumns();
            if (columns >= 9)
                for (int i = 1; i < row; i++) {
                    ExportEntity importEntity = new ExportEntity();

                    if (sheet.getRow(i).length > 0 && sheet.getRow(i)[0] != null && sheet.getRow(i)[0].getContents() != null)
                        importEntity.setCowNum(sheet.getRow(i)[0].getContents());
                    if (sheet.getRow(i).length > 3 && sheet.getRow(i)[3] != null && sheet.getRow(i)[3].getContents() != null)
                        importEntity.setBirthday(sheet.getRow(i)[3].getContents());
                    if (sheet.getRow(i).length > 2 && sheet.getRow(i)[2] != null && sheet.getRow(i)[2].getContents() != null)
                        importEntity.setCowfarmName(sheet.getRow(i)[2].getContents());
                    if (sheet.getRow(i).length > 1 && sheet.getRow(i)[1] != null && sheet.getRow(i)[1].getContents() != null)
                        importEntity.setCowfarmNum(sheet.getRow(i)[1].getContents());
                    if (sheet.getRow(i).length > 6 && sheet.getRow(i)[6] != null && sheet.getRow(i)[6].getContents() != null)
                        importEntity.setFather(sheet.getRow(i)[6].getContents());
                    if (sheet.getRow(i).length > 8 && sheet.getRow(i)[8] != null && sheet.getRow(i)[8].getContents() != null)
                        importEntity.setGrandfather(sheet.getRow(i)[8].getContents());
                    if (sheet.getRow(i).length > 7 && sheet.getRow(i)[7] != null && sheet.getRow(i)[7].getContents() != null)
                        importEntity.setMother(sheet.getRow(i)[7].getContents());
                    if (sheet.getRow(i).length > 5 && sheet.getRow(i)[5] != null && sheet.getRow(i)[5].getContents() != null)
                        importEntity.setProductionTime(sheet.getRow(i)[5].getContents());
                    if (sheet.getRow(i).length > 4 && sheet.getRow(i)[4] != null && sheet.getRow(i)[4].getContents() != null)
                        importEntity.setTyre(sheet.getRow(i)[4].getContents());
                    StringBuffer sb = new StringBuffer();
                    for (int j = 0; j < 20; j++) {
                        int k = j + 9;
                        if (sheet.getRow(i).length > k && sheet.getRow(i)[k] != null && sheet.getRow(i)[k].getContents() != null) {
                            sb.append(sheet.getRow(i)[k].getContents());
                            sb.append(",");
                        } //else {
                            //sb.append("0");
                        //}

                    }
                    if(sb.length() >0)
                    importEntity.toPoint(sb.toString().substring(0, sb.length() - 1));
                    if (sheet.getRow(i).length > 29 && sheet.getRow(i)[29] != null && sheet.getRow(i)[29].getContents() != null)
                        try {
                            importEntity.setTiqurongliang(Float.parseFloat(sheet.getRow(i)[29].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setTiqurongliang(0.0f);
                        }
                    if (sheet.getRow(i).length > 30 && sheet.getRow(i)[30] != null && sheet.getRow(i)[30].getContents() != null)
                        try {
                            importEntity.setKaobu(Float.parseFloat(sheet.getRow(i)[30].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setKaobu(0.0f);
                        }
                    if (sheet.getRow(i).length > 31 && sheet.getRow(i)[31] != null && sheet.getRow(i)[31].getContents() != null)
                        try {
                            importEntity.setZhiti(Float.parseFloat(sheet.getRow(i)[31].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setZhiti(0.0f);
                        }
                    if (sheet.getRow(i).length > 32 && sheet.getRow(i)[32] != null && sheet.getRow(i)[32].getContents() != null)
                        try {
                            importEntity.setXitong(Float.parseFloat(sheet.getRow(i)[32].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setXitong(0.0f);
                        }
                    if (sheet.getRow(i).length > 33 && sheet.getRow(i)[33] != null && sheet.getRow(i)[33].getContents() != null)
                        try {
                            importEntity.setQianrufang(Float.parseFloat(sheet.getRow(i)[33].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setQianrufang(0.0f);
                        }
                    if (sheet.getRow(i).length > 34 && sheet.getRow(i)[34] != null && sheet.getRow(i)[34].getContents() != null)
                        try {
                            importEntity.setHourufang(Float.parseFloat(sheet.getRow(i)[34].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setHourufang(0.0f);
                        }
                    if (sheet.getRow(i).length > 35 && sheet.getRow(i)[35] != null && sheet.getRow(i)[35].getContents() != null)
                        try {
                            importEntity.setRuyongtezheng(Float.parseFloat(sheet.getRow(i)[35].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setRuyongtezheng(0.0f);
                        }
                    if (sheet.getRow(i).length > 36 && sheet.getRow(i)[36] != null && sheet.getRow(i)[36].getContents() != null)
                        try {
                            importEntity.setAverage(Float.parseFloat(sheet.getRow(i)[36].getContents()));
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            importEntity.setAverage(0.0f);
                        }
                    info.add(importEntity);
                }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

    public boolean createTempXls(String fileName, List<ExportEntity> dataList) {
        boolean success = true;
        WritableWorkbook wwb = null;
        try {
            //创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(fileName));
        } catch (IOException e) {
            success = false;
            e.printStackTrace();
        }
        if (wwb != null) {
            // 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
            WritableSheet ws = wwb.createSheet("sheet1", 0);
            for (int i = 0; i < ExportActivity.columnName.length; i++) {
                Label lbl = new Label(i, 0, ExportActivity.columnName[i]);
                try {
                    ws.addCell(lbl);
                } catch (RowsExceededException e1) {
                    e1.printStackTrace();
                    success = false;
                } catch (WriteException e1) {
                    e1.printStackTrace();
                    success = false;
                }
            }
            for (int i = 0; i < dataList.size(); i++) {
                int modifyPos = i + 1;
                ExportEntity exportEntity = dataList.get(i);
                Label lbl1 = new Label(0, modifyPos, exportEntity.getCowNum());
                Label lbl2 = new Label(1, modifyPos, exportEntity.getCowfarmNum());
                Label lbl3 = new Label(2, modifyPos, exportEntity.getCowfarmName());
                Label lbl4 = new Label(3, modifyPos, exportEntity.getBirthday());
                Label lbl5 = new Label(4, modifyPos, exportEntity.getTyre());
                Label lbl6 = new Label(5, modifyPos, exportEntity.getProductionTime());
                Label lbl7 = new Label(6, modifyPos, exportEntity.getFather());
                Label lbl8 = new Label(7, modifyPos, exportEntity.getMother());
                Label lbl9 = new Label(8, modifyPos, exportEntity.getGrandfather());

                try {
                    ws.addCell(lbl1);
                    ws.addCell(lbl2);
                    ws.addCell(lbl3);
                    ws.addCell(lbl4);
                    ws.addCell(lbl5);
                    ws.addCell(lbl6);
                    ws.addCell(lbl7);
                    ws.addCell(lbl8);
                    ws.addCell(lbl9);
                } catch (RowsExceededException e1) {
                    e1.printStackTrace();
                    success = false;
                } catch (WriteException e1) {
                    e1.printStackTrace();
                    success = false;
                }
                if (exportEntity.getColumnValue() != null && exportEntity.getColumnValue().length > 0)
                    for (int j = 0; j < exportEntity.getColumnValue().length; j++) {
                        if (exportEntity.getColumnValue()[j] > 0) {
                            Label lbl = new Label(j + 9, modifyPos, String.valueOf(exportEntity.getColumnValue()[j]));
                            try {
                                ws.addCell(lbl);
                            } catch (RowsExceededException e1) {
                                e1.printStackTrace();
                                success = false;
                            } catch (WriteException e1) {
                                e1.printStackTrace();
                                success = false;
                            }
                        }
                    }


                try {
                    if (exportEntity.getTiqurongliang() > 0.0f) {
                        Label lbl10 = new Label(29, modifyPos, exportEntity.getTiqurongliang() + "");
                        ws.addCell(lbl10);
                    }
                    if (exportEntity.getKaobu() > 0.0f) {
                        Label lbl11 = new Label(30, modifyPos, exportEntity.getKaobu() + "");
                        ws.addCell(lbl11);
                    }
                    if (exportEntity.getZhiti() > 0.0f) {
                        Label lbl12 = new Label(31, modifyPos, exportEntity.getZhiti() + "");
                        ws.addCell(lbl12);
                    }
                    if (exportEntity.getXitong() > 0.0f) {
                        Label lbl13 = new Label(32, modifyPos, exportEntity.getXitong() + "");
                        ws.addCell(lbl13);
                    }
                    if (exportEntity.getQianrufang() > 0.0f) {
                        Label lbl14 = new Label(33, modifyPos, exportEntity.getQianrufang() + "");
                        ws.addCell(lbl14);
                    }
                    if (exportEntity.getHourufang() > 0.0f) {
                        Label lbl15 = new Label(34, modifyPos, exportEntity.getHourufang() + "");
                        ws.addCell(lbl15);
                    }
                    if (exportEntity.getRuyongtezheng() > 0.0f) {
                        Label lbl16 = new Label(35, modifyPos, exportEntity.getRuyongtezheng() + "");
                        ws.addCell(lbl16);
                    }
                } catch (RowsExceededException e1) {
                    e1.printStackTrace();
                    success = false;
                } catch (WriteException e1) {
                    e1.printStackTrace();
                    success = false;
                }
                if (exportEntity.getAverage() > 0.0f) {
                    Label lbl11 = new Label(36, modifyPos, String.valueOf(exportEntity.getAverage()));
                    try {
                        ws.addCell(lbl11);
                    } catch (RowsExceededException e1) {
                        success = false;
                        e1.printStackTrace();
                    } catch (WriteException e1) {
                        e1.printStackTrace();
                        success = false;
                    }
                }
            }
            try {
                wwb.write();
                wwb.close();
            } catch (IOException e) {
                success = false;
                e.printStackTrace();
            } catch (WriteException e) {
                success = false;
                e.printStackTrace();
            }
        }
        if (!success) {
            showMessage("导出失败,请确认录入数据是否正确!");
        }
        return success;
    }

    private void showMessage(String str) {
        Toast toast = new Toast(this);
        View toastView = LayoutInflater.from(this).inflate(R.layout.toast_text, null);
        TextView textView = (TextView) toastView.findViewById(R.id.toast_text);
        textView.setText(str);
        toast.setView(toastView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 10);
        toast.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fileParentPath != null && !fileParentPath.equals(ImportActivity.ROOT_FILE_PARENT_PATH)) {
                setCurrentFile(fileParentPath);
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
